////==============================================================================websocket begin
//初始化所需 用户信息
$websocketInitData = ajaxSynchroRequest('/api/index/websocket-init');
console.log($websocketInitData);
var is_login = 1;
if($websocketInitData.success === 0 && $websocketInitData.msg === "未登录"){
    is_login=0;
}
//获取用户登录的服务器信息
var music=document.getElementById("mymusic");
var server = "";
var usercode = "";
var userid = "";
var isconnected = 0;
if($websocketInitData.success == 1){
    server = $websocketInitData.data.server;
    usercode = $websocketInitData.data.usercode;
    userid = $websocketInitData.data.userid;
    username = $websocketInitData.data.username;
    headimg = $websocketInitData.data.headimg;
}else{
    var server = "";
    var usercode = "";
}
//console.log(server);
var ws;
if(server != "" && usercode != ""){
    var ws = new WebSocket("ws://"+server);
    //【用于指定连接成功后的回调函数】
    ws.onopen = function (evt) {
        console.log("Connection open ...");
        var json = {"sockettype":1,"usercode":usercode,"server":server,"msg_type":0}; //创建对象；
        var jsonStr = JSON.stringify(json);       //转为JSON字符串
        ws.send(jsonStr);       //首次发送 用户与服务器交互的信息
        isconnected = 1;
    };
    //[【于指定连接关闭后的回调函数。】
    ws.onclose = function (evt) {
        console.log("Connection closed.");
        isconnected = 0;
        ws.onopen = function (evt) {
            console.log("Connection open ...");
            var json = {"sockettype":1,"usercode":usercode,"server":server,"msg_type":0}; //创建对象；
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            ws.send(jsonStr);       //首次发送 用户与服务器交互的信息
            isconnected = 1;
        };
    };
    ws.onmessage = function (event) {
        console.log("index page Received Message: " + event.data);
        var msg = JSON.parse(event.data);//json字符串转化为对象
        dealmsg(msg);
    };
    //webSocket.onerror 用于指定报错时的回调函数
    ws.onerror = function (event) {
        window.location.reload();
        console.log(event);
        console.log("event error");
    };

    //每隔30秒检测长连接
    setInterval(function() {
        if(ws.readyState === 1){
            var json = {"1":1}; //创建对象；
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            ws.send(jsonStr);
        }else if(ws.readyState === 3){
            ws = new WebSocket("ws://"+server);
            //【用于指定连接成功后的回调函数】
            ws.onopen = function (evt) {
                console.log("Connection open ...");
                var json = {"sockettype":1,"usercode":usercode,"server":server,"msg_type":0}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串
                ws.send(jsonStr);       //首次发送 用户与服务器交互的信息
                isconnected = 1;
            };

            //[【于指定连接关闭后的回调函数。】
            ws.onclose = function (evt) {
                console.log("Connection closed.");
                isconnected = 0;
            };
            ws.onmessage = function (event) {
                //console.log("index page Received Message: " + event.data);
                var msg = JSON.parse(event.data);//json字符串转化为对象
                dealmsg(msg);
            };
        }
    }, 30000);
}
function dealmsg(msg){
    console.log(msg);
//    console.log("userid is " + userid);
    var msgnum = "";
    if(msg.touserid == userid){
        music.play();
        //msgnum = $('#msg-num').html() === "" ? 1 : parseInt($('#msg-num').html())+1;
        console.log("msg-num is :"+$('#msg-num').html())
        if($('#msg-num').html() === '0'){
            msgnum = 1;
        }
        else if(parseInt($('#msg-num').html()) >= 1 && parseInt($('#msg-num').html()) <= 98){
            msgnum = parseInt($('#msg-num').html())+1;
        }
        else{
            msgnum = 99;
        }
        $('#msg-num').html(msgnum);
        $('#msg-num').show();
        
        $('#commentnum_'+msg.worksid).html(parseInt($('#commentnum_'+msg.worksid).html())+1);
        
        //作品评论消息
        if(msg.msgcate == 1){
            if($('#unread-msg-list-'+msg.worksid).length == 0){
                var newmsghtml = '<div class="unread-msg-list" id="unread-msg-list-'+msg.worksid+'">'+
                    '<a href="/works/detail?worksid='+msg.worksid+'"><div class="unread-msg-list-totalnum" id="unread-msg-list-totalnum-'+msg.worksid+'"><span class="number-box">1</span></div>'+
                    '<div class="unread-msg-list-content" id="unread-msg-list-content-'+msg.worksid+'">'+msg.content+'</div>'+
                    '<div class="unread-msg-list-title" id="unread-msg-list-title-'+msg.worksid+'">《'+msg.title+'》</div>'+
                    '<div class="unread-msg-list-addtime" id="unread-msg-list-addtime-'+msg.worksid+'">刚刚</div></a>'+
                '</div>';

                $('#works-msg-outter').prepend(newmsghtml);
            }else{
                var detailnewnum = parseInt($('#unread-msg-list-totalnum-'+msg.worksid).find("span").eq(0).html())+1;
                $('#unread-msg-list-totalnum-'+msg.worksid).find("span").eq(0).html(detailnewnum);
                $('#unread-msg-list-content-'+msg.worksid).html(msg.content);
                $('#unread-msg-list-addtime-'+msg.worksid).html("刚刚");
            }
        }
        //添加好友消息
        if(msg.msgcate == 2){
            console.log("好友请求");
            var newrequesthtml = '<div class="request-msg-list" id="request-msg-list-'+msg.id+'"><div class="request-msg-title">好友申请</div>'+
            '<div class="request-msg-list-headimg-outter"><img class="request-msg-headimg" src="'+msg.headimg+'"/></div>'+
            '<div class="request-msg-list-username-outter" id="request-msg-list-content-'+msg.id+'"><span class="request-msg-list-username">'+msg.user+'</span>'+
                '<span class="request-msg-list-addtime">刚刚</span></div>'+
            '<div class="request-msg-list-option-outter"><span class="request-msg-list-option-accept" data-id="'+msg.id+'">接受</span><span class="request-msg-list-option-refuse" data-id="'+msg.id+'">拒绝</span></div></div>'
            
            $('#friends-request-outter').prepend(newrequesthtml);
        }
        //好友消息
        if(msg.msgcate == 3){
//            msg.headimg
//            msg.fromuserid
//            msg.msgcate
//            msg.msgtype
//            msg.sockettype
//            msg.touserid
            if($('#chat-msg-list-'+msg.chat_id).length == 0){
                var newchat_html = '<div class="chat-msg-list" id="chat-msg-list-'+msg.chat_id+'" data-id="'+msg.chat_id+'">'+
                '<div class="chat-friend-head-outter"><img class="chat-friend-headimg" src="'+msg.fromheadimg+'"/><span class="friend-unreadnum" id="friend-unreadnum-'+msg.chat_id+'">1</span></div>'+
            '<div class="chat-friend-body-outter"><span class="friend-name">'+msg.fromuser+'</span><span class="friend-msg" id="friend-msg-'+msg.chat_id+'">'+msg.content+'</span></div>'+
            '<div class="chat-time-outter" id="chat-time-outter-'+msg.chat_id+'">刚刚</div></div>';
                $('#friends-msg-outter').append(newchat_html);
            }else{
                var single_unread = parseInt($('#friend-unreadnum-'+msg.chat_id).html())+1;
                $('#friend-unreadnum-'+msg.chat_id).html(single_unread);
                $('#friend-unreadnum-'+msg.chat_id).show();
                $('#friend-msg-'+msg.chat_id).html(msg.content);
                $('#chat-time-outter-'+msg.chat_id).html("刚刚");
                
                if(single_unread==1){
                    var newChat = $('#chat-msg-list-'+msg.chat_id);
                    $('#chat-msg-list-'+msg.chat_id).remove();
                    $('#friends-msg-outter').prepend(newChat);
                }
            }
            
        }
        if(msg.msgcate == 4){//好友验证通过消息
            new_friend_html = '<div class="friend-item" data-chatid="'+msg.chat_id+'" data-head="'+msg.fromheadimg+'" data-remarks="'+msg.fromuser+'"><div class="friend-head-area"><img class="headimg" src="'+msg.fromheadimg+'"/></div><div class="friend-body-area">'+msg.fromuser+'</div></div>';
            $('#friends-list').prepend(new_friend_html);
        }
        
        $('#msg-none').hide();
    }
}
//==============================================================================websocket end

$(document).ready(function(){
    
    //当前连接拆分
    $href = window.location.href;
    $newhref = $href.split("#");
    $(".indexpages").each(function(){
        $(this).hide();
    });
//    console.log($newhref);
    if(typeof($newhref[1]) == "undefined"){
        $('#button-page-index').trigger('click');
    }else if($newhref[1] == "home"){
        $('#button-page-index').trigger('click');
        
    }else if($newhref[1] == "friend"){
        $('#button-page-friends').trigger('click');
    }else if($newhref[1] == "publish"){
        $('#button-page-publish').trigger('click');
    }else if($newhref[1] == "msg"){
        $('#button-page-msg').trigger('click');
    }else if($newhref[1] == "mine"){
        $('#button-page-mine').trigger('click');
    }
    
    if(parseInt($('#msg-num').html()) == 0){
        $('#msg-num').hide();
        if($('#msg-none').length !== 0){$('#msg-none').show();}
    }
        
    $("#indexpage-works").on('click','.music-button',function(){
        var worksid = $(this).attr('data-id');
        var title = $(this).attr('data-title');
        var author = $(this).attr('data-author');
        var authorid = $(this).attr('data-authorid');
        if(is_login === 0){
            window.location.href = "/site/login?returnurl=/#home";
        }
        contentHtml = '<div class="works-comment-view-layout"><div class="comment-content-edit"><form id="music_form" action="/user/default/uploadmusic" method="post" enctype="multipart/form-data"><input type="hidden" name="worksid" value="'+worksid+'"/><input type="hidden" name="authorid" value="'+authorid+'"/><input type="file" id="music" name="music"></form></div><div class="comment-button-area"><div class="comment-cancel" onclick="layer.close($musicview);">取消</div><div class="comment-submmit" id="music-submmit">提交</div></div></div>';

        $musicview = layer.open({
            type: 1
            ,content: contentHtml
            ,anim: 'right'
            ,style: 'position:fixed;float:left; left:0%;top:20%; width:100%;border: 1px solid #ccc;border-radius: 20px;padding-top:10px;'
          });
          
          $('#music-submmit').on('click',function(){
            //$("#music_form").submit();
            data = new FormData($("#music_form")[0]);
//            console.log(data);return false;
            $.ajax({
                url: "/user/default/uploadmusic",
                type: "post",
                dataType: "json",
                cache: false,
                data: data,
                processData: false,// 不处理数据
                contentType: false, // 不设置内容类型
                success: function(data){
                    if(data.success == 1){
                        layer.open({
                            content: data.msg
                            ,skin: 'msg'
                            ,time: 4 //3秒后自动关闭
                        });
                        layer.close($musicview);
                    }
                    console.log(data);
                }
            })
          });
    });
    
    $("#indexpage-works").on('click','.comment-button',function(){
        var worksid = $(this).attr('data-id');
        var title = $(this).attr('data-title');
        var author = $(this).attr('data-author');
        var authorid = $(this).attr('data-authorid');

        console.log(title);
        //检测登录情况
        if(is_login === 0){
            window.location.href = "/site/login?returnurl=/#home";
        }
        //评论弹出层
        //自定义标题风格
        contentHtml = '<div class="works-comment-view-layout"><div class="comment-content-edit"><textarea id="comment-content" class="comment-content-textarea" placeholder="编写评论..."></textarea></div><div class="comment-button-area"><div class="comment-cancel" onclick="layer.close($commentview);">取消</div><div class="comment-submmit" id="comment-submmit">提交</div></div></div>';

        $commentview = layer.open({
            type: 1
            ,content: contentHtml
            ,anim: 'right'
            ,style: 'position:fixed;float:left; left:0%;top:20%; width:100%;border: 1px solid #ccc;border-radius: 20px;padding-top:10px;'
          });

        $('.comment-submmit').on('click',function(){
            var comment_content = $('#comment-content').val();
            $params = JSON.stringify({'worksid':worksid,'author':author,'authorid':authorid,'content':comment_content,'type':1});

            $comment_back = ajaxSynchroRequest("/api/works/comment",$params);
            console.log($comment_back);
            if($comment_back.success == 0){
                layer.open({
                    content: $comment_back.msg
                    ,skin: 'msg'
                    ,time: 4 //3秒后自动关闭
                });
                return false;
            }
            
            if($comment_back.userid != $comment_back.touserid && ws.readyState === 1){//非作者评论，推送消息
                //msgcate评论消息
                var json = {'sockettype':3,'worksid':worksid,'title':title,'msgcate':1,'msgtype':'text','content':comment_content,'user':$comment_back.user,'userid':$comment_back.userid,'touserid':$comment_back.touserid}; //创建对象；
                var jsonStr = JSON.stringify(json);       //转为JSON字符串
                ws.send(jsonStr);
            }
            //关闭评论层
            layer.close($commentview);
            $('#commentnum_'+worksid).html(parseInt($('#commentnum_'+worksid).html())+1);
        });
    });
    //查看评论详情
    $("#indexpage-works").on('click','.comment-num',function(){
        var worksid = $(this).attr('data-id');
        //console.log("comment nums "+worksid);
        window.location.href = '/works/detail?worksid='+worksid;
    });
    //收藏
    $("#indexpage-works").on('click','.shoucang',function(){
        if(is_login === 0){
            window.location.href = "/site/login?returnurl=/#home";
        }
        var worksid = $(this).attr('data-id');
        console.log("喜欢： "+worksid);
        $params = JSON.stringify({'worksid':worksid});
        $collection_back = ajaxSynchroRequest("/api/works/collection",$params);
        console.log($collection_back);
        if($collection_back.success == 1){
            if($collection_back.code == 1){
                $("#like-"+worksid).removeClass("uncollectioned");
                $("#like-"+worksid).addClass("collectioned")
                
                $("#collectnum_"+worksid).html(parseInt($('#collectnum_'+worksid).html())+1);
            }else{
                $("#like-"+worksid).removeClass("collectioned");
                $("#like-"+worksid).addClass("uncollectioned")
                $("#collectnum_"+worksid).html(parseInt($('#collectnum_'+worksid).html())-1);
            }
        }
    });
    
    $("#indexpage-works").on('click','.headimg-area',function(){
        var id = $(this).attr('data-id');
        console.log(id);
    });
    
    $("#indexpage-works").on('click','.works-auther',function(){
        var id = $(this).attr('data-id');
        console.log(id);
    });

    $('#publish-submit').on('click',function(){
        console.log($('#title').val());
        console.log($('#content').val());
        $title = $('#title').val();
        $content = $('#content').val();
        $category = $('#category').val();
        $params = JSON.stringify({'title':$title,'content':$content,'category':$category});

        $publish = ajaxSynchroPostRequest("/api/works/publish",$params);
        if($publish.success === 1){
            layer.open({
                content: $publish.msg
                ,skin: 'msg'
                ,time: 4 //3秒后自动关闭
            });
            setTimeout(function () {
                $('#title').val("");
                $('#content').val("");
                $('#button-page-index').trigger('click');
            }, 2000);

        }else{
            layer.open({
                content: $publish.msg
                ,skin: 'msg'
                ,time: 3 //3秒后自动关闭
            });
        }
        console.log($publish);
    });

    
    $('#friend-add').on('click',function(){
        contentHtml = '<div class="friends-add-layout"><div class="friends-search"><input id="userinfo" class="friends-search-input" placeholder="手机号码/用户名"/><span class="friends-search-submit" id="friends-search-submit">搜索</span><span class="friends-search-cancel" id="friends-search-cancel"  onclick="layer.close($friend_add_view);">×</span></div><div id="search-result" class="search-result"></div></div>';

        $friend_add_view = layer.open({
            type: 1
            ,content: contentHtml
            ,anim: 'right'
            ,style: 'position:fixed; left:0%; top:20%; width:100%; height:auto; border: none;'
          });
          
        $('#friends-search-submit').on('click',function(){
            var userinfo = $('#userinfo').val();
            
            $params = JSON.stringify({'userinfo':userinfo});

            $search_back = ajaxSynchroRequest("/api/friends/search",$params);
            
            
            console.log($search_back);
            if($search_back.success == 1){
                var headimg = $search_back.data.headimg == "" ? "/img/user/default-head.png" : $search_back.data.headimg;
                $search_back.data.userid
                $search_back.data.username
                var add_html = '<div class="user-search-outter"><div class="user-search-headimg-outter"><img class="user-search-headimg" src="'+headimg+'"/><span class="user-search-username">'+$search_back.data.username+'</span></div><div class="user-add-button-outter" id="user-add-button-outter"><span class="user-add-button" id="user-add-button" data-id="'+$search_back.data.userid+'">添加</span></div></div>';
                $('#search-result').html(add_html);
            }
            else if($search_back.success == 0){//未登录
                window.location.href = "/site/login?returnurl=/#friend";
            }else if($search_back.success == 2){//不存在用户
                var not_exits_html = '<div class="not-exist">'+$search_back.msg+'</div>';
                $('#search-result').html(not_exits_html);
            }
            
            $('#user-add-button').on('click',function(){
                var userid = $(this).attr('data-id');
                console.log(userid);
                $params = JSON.stringify({'userid':userid});

                $add_back = ajaxSynchroRequest("/api/friends/add",$params);
                console.log($add_back);
                if($add_back.success == 1){
                    $('#user-add-button').hide();
                    var reqeusted_html = '<span class = "user-requested">已申请</span>';
                    $('#user-add-button-outter').append(reqeusted_html);
                    //发送即时消息
                    var json = {'sockettype':3,'msgcate':2,'msgtype':'text','content':'好友请求','id':$add_back.data.id,'user':$add_back.data.username,'userid':$add_back.data.userid,'headimg':$add_back.data.headimg,'touserid':$add_back.data.touserid}; //创建对象；
                    var jsonStr = JSON.stringify(json);       //转为JSON字符串
                    ws.send(jsonStr);
                }
                else{
                    layer.open({
                        content: $add_back.msg
                        ,skin: 'msg'
                        ,time: 3 //3秒后自动关闭
                    });
                }
            });
        });
    });
    //接受好友请求
    $("#friends-request-outter").on('click','.request-msg-list-option-accept',function(){
        var request_id = $(this).attr('data-id');
        $params = JSON.stringify({'id':request_id});
        $add_back = ajaxSynchroRequest("/api/friends/accept",$params);
        console.log($add_back);
        layer.open({
            content: $add_back.msg
            ,skin: 'msg'
            ,time: 3 //3秒后自动关闭
        });
        
        if($add_back.success == 1){
            msgnum = parseInt($('#msg-num').html())-1;
            if(msgnum != 0){$('#msg-num').html(msgnum);}else{$('#msg-num').hide();}
            $("#request-msg-list-"+request_id).remove();
            //生成会话，发送即时消息
            
            $params = JSON.stringify({'user1':$add_back.data.user,'user2':userid,});
            $create_chat_back = ajaxSynchroRequest("/api/friends/create-chat",$params);
            
            //生成会话项
            new_chat_html = '<div class="chat-msg-list" id="chat-msg-list-'+$create_chat_back.chat_id+'" data-id="'+$create_chat_back.chat_id+'">'+
            '<div class="chat-friend-head-outter"><img class="chat-friend-headimg" src="'+$create_chat_back.friend_head+'"/>'+
                '<span class="friend-unreadnum no-unread" id="friend-unreadnum-'+$create_chat_back.chat_id+'"></span></div>'+
            '<div class="chat-friend-body-outter"><span class="friend-name">'+$create_chat_back.friend_name+'</span>'+
                '<span class="friend-msg" id="friend-msg-'+$create_chat_back.chat_id+'">'+$create_chat_back.content+'</span></div>'+
            '<div class="chat-time-outter" id="chat-time-outter-'+$create_chat_back.chat_id+'">刚刚</div></div>';
            
            $('#friends-msg-outter').append(new_chat_html);
            
            //好友列表项写入
            new_friend_html = '<div class="friend-item" data-chatid="'+$create_chat_back.chat_id+'" data-head="'+$create_chat_back.friend_head+'" data-remarks="'+$create_chat_back.friend_name+'"><div class="friend-head-area"><img class="headimg" src="'+$create_chat_back.friend_head+'"/></div><div class="friend-body-area">'+$create_chat_back.friend_name+'</div></div>';
            $('#friends-list').prepend(new_friend_html);
            
            //通知好友已通过
            var json = {'sockettype':3,'msgcate':4,'msgtype':'text','content':'success','chat_id':$create_chat_back.chat_id,'fromuser':username,'fromuserid':userid,'fromheadimg':headimg,'touserid':$create_chat_back.friend_id}; //创建对象；
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            ws.send(jsonStr);
            //发送即时消息
            var json = {'sockettype':3,'msgcate':3,'msgtype':'text','content':$create_chat_back.content,'chat_id':$create_chat_back.chat_id,'fromuser':username,'fromuserid':userid,'fromheadimg':headimg,'touserid':$create_chat_back.friend_id}; //创建对象；
            var jsonStr = JSON.stringify(json);       //转为JSON字符串
            ws.send(jsonStr);
        }
    });
    //拒绝好友请求
    $("#friends-request-outter").on('click','.request-msg-list-option-refuse',function(){
        var request_id = $(this).attr('data-id');
        if(confirm("拒绝此人添加好友吗")){
            $params = JSON.stringify({'id':request_id});
            $refuse_back = ajaxSynchroRequest("/api/friends/refuse",$params);
            if($refuse_back.success == 1){
                msgnum = parseInt($('#msg-num').html())-1;
                if(msgnum != 0){
                    $('#msg-num').html(msgnum);
                }else{
                    $('#msg-num').hide();
                    if($('#msg-none').length !== 0){$('#msg-none').show();}
                }
                $("#request-msg-list-"+request_id).remove();
            }
        }
    });
    $("#friends-msg-outter").on('click','.chat-msg-list',function(){
        var chat_id = $(this).attr('data-id');
        var new_num = parseInt($('#msg-num').html())-parseInt($("#friend-unreadnum-"+chat_id).html());
        $("#friend-unreadnum-"+chat_id).html("0");
        $("#friend-unreadnum-"+chat_id).hide();
        $('#msg-num').html(new_num);
        if(new_num == 0){
            $('#msg-num').hide();
        }
        window.location.href = '/chat/default?chatid='+chat_id;	
    });
    //好友点击
    $(".friends-list").on('click','.friend-item',function(){
        var chatid = $(this).attr('data-chatid');
        
        contentHtml = '<div class="friend-sendmsg" data-chatid="'+chatid+'">发消息</div><div class="friend-click-cancel" onclick="layer.close($friendview);">取消</div>';
        $friendview = layer.open({
            type: 1
            ,content: contentHtml
            ,anim: 'right'
            ,style: 'position:fixed; left:0%; top:20%; width:100%; height:auto; border: none;'
          });
        
        
        $(".friend-sendmsg").on('click',function(){
            //获取好友会话信息chatid
            if(chatid != 0){
                window.location.href = '/chat/default?chatid='+chatid;
            }
        });
    });
    
});
//分类
var category = 0;
var page = 1; //分页码
var pagedata_on = true; //分页开关(滚动加载方法 1 中用的)
$('.indexpage-category-item').on('click',function(){
    page = 1;
    category = $(this).attr('data-id');
    $(".indexpage-category-item").each(function(){
        $(this).removeClass("indexpage-category-item-selected");
    });
    if(category == -1 && is_login == 0){
        window.location.href = '/site/login';
    }
    $(this).addClass("indexpage-category-item-selected");
    $params = JSON.stringify({'page':page,'category':category});
    $works = ajaxSynchroRequest("/site/workspage",$params);
    var newWorksHtml = '';
    if($works.success == 1){
        $('#works-none').hide();
        pagedata_on = true;
        $('#indexpage-works').empty();
        if($works.data.length != 0){
            console.log($works);
            $.each($works.data,function(index,value){
                newWorksHtml += '<div class="works-outter"><div class="works-head"><a href="/user/home/index?id='+value.authorid+'"><div class="headimg-area"><img src="'+value.userheadimg+'" class="works-user-headimg"/></div><div class="works-auther"><div class="auther-name">'+value.author+'</div><div class="works-time">'+value.addtime+'</div></div></a></div>'
                newWorksHtml += '<div class="works-body"><a href="/works/detail?worksid='+value.id+'"><div class="works-title">《'+value.title+'》</div><div class="works-content" data-id="'+value.id+'">'+value.content+'</div></a></div>'
                var iscollect = value.is_collection===true?"collectioned":"uncollectioned";
                newWorksHtml += '<div class="comment-area"><span class="music-button"  data-id="'+value.id+'" data-title="'+value.title+'" data-author="'+value.author+'" data-authorid="'+value.authorid+'">+谱曲</span><span class="comment-button"  data-id="'+value.id+'" data-title="'+value.title+'" data-author="'+value.author+'" data-authorid="'+value.authorid+'"></span><span class="comment-num" id="commentnum_'+value.id+'" data-id="'+value.id+'">'+value.comment_num+'</span><span class="shoucang '+iscollect+'" id="like-'+value.id+'" data-id="'+value.id+'"></span><span class="comment-num" id="collectnum_'+value.id+'" data-id="'+value.id+'">'+value.collect_num+'</span></div></div>'
                
//                newWorksHtml += '<div class="works-outter"><div class="headimg-area" data-id="'+value.authorid+'"><img src="'+value.userheadimg+'" class="works-user-headimg"/></div>';
//                newWorksHtml += '<div class="works-area"><div class="works-auther" data-id="'+value.authorid+'">'+value.author+'</div>';
//                newWorksHtml += '<div class="works-title">'+value.title+'</div><div class="works-content" data-id="'+value.id+'">'+value.content+'</div></div>';
//                var iscollect = value.is_collection===true?"collectioned":"";
//                newWorksHtml += '<div class="comment-area"><span class="comment-button"  data-id="'+value.id+'" data-title="'+value.title+'" data-author="'+value.author+'" data-authorid="'+value.authorid+'">评论</span>（<span class="comment-num" id="commentnum_'+value.id+'" data-id="'+value.id+'">'+value.comment_num+'</span>） <span class="shoucang '+iscollect+'" id="like-'+value.id+'" data-id="'+value.id+'">喜欢</span></div></div>';
            });
            $('#indexpage-works').append(newWorksHtml);
        }else{
            $('#works-none').show();
        }
    }
});
var all_category_show = false;
$('#indexnav-arrow').on('click',function(){
    if(all_category_show === false){
        $('#indexpage-all-category-outter').show();
        $('#more-arrow').removeClass("more-unclick");
        $('#more-arrow').addClass("more-click");
        all_category_show = true;
    }else{
        $('#indexpage-all-category-outter').hide();
        $('#more-arrow').removeClass("more-click");
        $('#more-arrow').addClass("more-unclick");
        all_category_show = false;
    }
})
$('.indexpage-all-category-item').on('click',function(){
    category = $(this).attr('data-id');
    $('#category-scroll-'+category).click();
    $('#category-scroll-'+category).scrollLeft(10000);
    $('#indexpage-all-category-outter').hide();
    all_category_show = false;
});

function init_bottom_buttons(){
    $('#button-page-index').removeClass("footer-index-selected");
    $('#button-page-index').addClass("footer-index-unselected");

    $('#button-page-friends').removeClass("footer-friends-selected");
    $('#button-page-friends').addClass("footer-friends-unselected");

    $('#button-page-publish').removeClass("footer-publish-selected");
    $('#button-page-publish').addClass("footer-publish-unselected");

    $('#button-page-msg').removeClass("footer-msg-selected");
    $('#button-page-msg').addClass("footer-msg-unselected");

    $('#button-page-mine').removeClass("footer-mine-selected");
    $('#button-page-mine').addClass("footer-mine-unselected");
}
//首页按钮
$('#button-page-index').on('click',function(){
    //改变按钮样式
    init_bottom_buttons();
    $("#button-page-index").removeClass("footer-index-unselected");
    $("#button-page-index").addClass("footer-index-selected");
    //页面展示
    $(".indexpages").each(function(){
        $(this).hide();
    });
    $("#homepage").show();
    
    //timers = null; //定时器(滚动加载方法 2 中用的)
    $(window).scroll(function() {
        //当时滚动条离底部60px时开始加载下一页的内容
        if (($(window).height() + $(window).scrollTop() + 60) >= $(document).height()) {
            //clearTimeout(timers);
            console.log("第" + page + "页");
            if(pagedata_on === true){
                $('#works-none').hide();
                page++;
                $params = JSON.stringify({'page':page,'category':category});
                $works = ajaxSynchroRequest("/site/workspage",$params);
                var newWorksHtml = '';
                console.log($works);
                if($works.success == 1){
                    if($works.data.length != 0){
                        $.each($works.data,function(index,value){
                            newWorksHtml += '<div class="works-outter"><div class="works-head"><a href="/user/home/index?id='+value.authorid+'"><div class="headimg-area"><img src="'+value.userheadimg+'" class="works-user-headimg"/></div><div class="works-auther"><div class="auther-name">'+value.author+'</div><div class="works-time">'+value.addtime+'</div></div></a></div>'
                            newWorksHtml += '<div class="works-body"><a href="/works/detail?worksid='+value.id+'"><div class="works-title">《'+value.title+'》</div><div class="works-content" data-id="'+value.id+'">'+value.content+'</div></a></div>'
                            var iscollect = value.is_collection===true?"collectioned":"uncollectioned";
                            newWorksHtml += '<div class="comment-area"><span class="music-button"  data-id="'+value.id+'" data-title="'+value.title+'" data-author="'+value.author+'" data-authorid="'+value.authorid+'">+谱曲</span><span class="comment-button"  data-id="'+value.id+'" data-title="'+value.title+'" data-author="'+value.author+'" data-authorid="'+value.authorid+'"></span><span class="comment-num" id="commentnum_'+value.id+'" data-id="'+value.id+'">'+value.comment_num+'</span><span class="shoucang '+iscollect+'" id="like-'+value.id+'" data-id="'+value.id+'"></span><span class="comment-num" id="collectnum_'+value.id+'" data-id="'+value.id+'">'+value.collect_num+'</span></div></div>'
                        });
                        $('#indexpage-works').append(newWorksHtml);
                    }else{
                        pagedata_on = false;//关闭滚动加载
                        console.log("pagedata_on is "+pagedata_on);
                        console.log("没有啦！"+$works.data.length);
                        $('#works-none').show();
                    }
                }
            }
//            timers = setTimeout(function() {
//                
//            }, 100);
        }
    });
});
//好友按钮
$('#button-page-friends').on('click',function(){
    if(is_login === 0){
        window.location.href = "/site/login?returnurl=/#friends";
    }
    init_bottom_buttons();
    $("#button-page-friends").removeClass("footer-friends-unselected");
    $("#button-page-friends").addClass("footer-friends-selected");
    
    $(".indexpages").each(function(){
        $(this).hide();
    });
    $("#friendpage").show();
});
//发布按钮
$('#button-page-publish').on('click',function(){
    init_bottom_buttons();
    $("#button-page-publish").removeClass("footer-publish-unselected");
    $("#button-page-publish").addClass("footer-publish-selected");
    

//    $loginResult = ajaxSynchroRequest('/api/index/checklogin');
//    if($loginResult.success === 0){
//        window.location.href = "/site/login?returnurl=/#publish";
//    }
    if(is_login === 0){
        window.location.href = "/site/login?returnurl=/#publish";
    }
    $(".indexpages").each(function(){
            $(this).hide();
        });
    $("#publishpage").show();
});
//个人中心主页按钮
//$('#button-page-mine').on('click',function(){
//    $(".footer-item").each(function(){
//        $(this).removeClass("footer-selected");
//    });
//    $("#button-page-mine").addClass("footer-selected");
//
//    $userinfo = ajaxSynchroRequest('/api/user/index');
//    console.log($userinfo);
//    if($userinfo.success == 1){
//        $("#user-name").html($userinfo.data.username);
//        $("#mine-works-num").html($userinfo.data.worksnum);
//        $("#mine-collect-num").html($userinfo.data.collectnum);
//        $("#mine-collect-num").html($userinfo.data.collectnum);
//        if($userinfo.data.headimg != ""){
//            $("#mine-headimg").attr("src",$userinfo.data.headimg)
//        }
//
//        $(".indexpages").each(function(){
//            $(this).hide();
//        });
//        $("#minepage").show();
//    }
//    else if($userinfo.success == 0){
//        layer.open({
//            content: $userinfo.msg
//            ,skin: 'msg'
//            ,time: 3 //3秒后自动关闭
//        });
//        window.location.href = "/site/login?returnurl=/#mine";
//    }
//
//
//    $('#logout-submit').on('click',function(){
//        $('#logout-form').submit();
//    });
//});
//消息按钮
$('#button-page-msg').on('click',function(){
    if(is_login === 0){
        window.location.href = "/site/login?returnurl=/#msg";
    }
    init_bottom_buttons();
    $("#button-page-msg").removeClass("footer-msg-unselected");
    $("#button-page-msg").addClass("footer-msg-selected");

    //页面展示
    $(".indexpages").each(function(){
        $(this).hide();
    });
    $("#msgpage").show();
});